//
//  SWTabBar.swift
//  SinaWeibo
//
//  Created by AenyMo on 16/3/30.
//  Copyright © 2016年 AenyMo. All rights reserved.
//

import UIKit

class SWTabBar: UITabBar {

    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加中间按钮
        addSubview(composeButton)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        //如果不是纯代理创建,程序直接崩溃
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 布局子控件
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //重新布局子空间
        let btnW = bounds.width / 5
        let btnH = bounds.height
        let frame = CGRect(x: 0, y: 0, width: btnW, height: btnH)
        var btnIndex: CGFloat = 0
        
        //遍历子控件
        for subview in subviews {
            //判断是否是 UITabBarButton
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置偏移量
                subview.frame = CGRectOffset(frame, btnIndex * btnW, 0)

                btnIndex += btnIndex == 1 ? 2 : 1
            }
        }
        //设置偏移量
        composeButton.frame = CGRectOffset(frame, 2 * btnW, 0)
    }
    
    //MARK: - 懒加载 中间按钮
    lazy var composeButton: UIButton = {
        
        //创建按钮
        let composeBtn = UIButton()
        //设置背景
        composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //设置图片
        composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        composeBtn.sizeToFit()
        
        return composeBtn
    }()
    

}
